package com.setup.trac.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class FormDispatcherController extends SimpleFormController {

	
	private Map<String, Validator> ticketValidators = new HashMap<String, Validator>();
	private Map<String, AbstractTracFormController> formControllers = new HashMap<String, AbstractTracFormController>();
	@Override
	protected void onBind(HttpServletRequest request, Object command,
			BindException errors) throws Exception {
		String uri = getKey(request);
		Validator validator = ticketValidators.get(uri);
		if (validator != null && isValidateOnBinding()
				&& !suppressValidation(request, command, errors)) {
			ValidationUtils
					.invokeValidator(validator, command, errors);
		}
		onBindAndValidate(request, command, errors);
	}

	private String getKey(HttpServletRequest request) {
		String uri = request.getRequestURI();
		uri = uri.substring(uri.lastIndexOf("/") + 1);
		return uri;
	}

	public Map<String, Validator> getTicketValidators() {
		return ticketValidators;
	}

	public void setTicketValidators(Map<String, Validator> ticketValidators) {
		this.ticketValidators = ticketValidators;
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		
		return getController(request).onSubmit(request, response, command, errors);
	}

	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors, Map controlModel)
			throws Exception {
		// TODO Auto-generated method stub
		AbstractTracFormController controller = getController(request);
		return controller.showForm(request, response, errors, controlModel);
	}

	private AbstractTracFormController getController(HttpServletRequest request) {
		AbstractTracFormController controller = formControllers.get(getKey(request));
		return controller;
	}

	public Map<String, AbstractTracFormController> getFormControllers() {
		return formControllers;
	}

	public void setFormControllers(
			Map<String, AbstractTracFormController> formControllers) {
		this.formControllers = formControllers;
	}

}
